// 购物车模块
import axios from 'axios'
const cartModules = {
    // 开启命名空间
    namespaced:true,
    // state 需要写成函数，和组件中的data一样
    state() {
        return {
            goodList: [],
        }
    },
    mutations: {
        setGoodsList(state,newList) {
            state.goodList= newList
        },
       //  goods_state
       //  设置指定对象的状态，让它的状态与小选矿的状态保持一致
       //  因为是多个参数，所以后两个参数写成对象
        setGoodsItenmState(state,obj) {
            state.goodList[obj.index].goods_state = obj.checked
        },
        setGoodsListState(state,checked) {
            state.goodList.forEach(item=>item.goods_state=checked)
        },
        addCount(state,index) {
            state.goodList[index].goods_count++
        },
        subCount(state,index) {
            state.goodList[index].goods_count--
        }
    },
    actions: {
      async asyncSetGoodsList(store) {
           //  1.发送Ajax请求
           //  2.把后台相应的数据，commit到mutations里面
          const res = await axios({
                method:'GET',
                url:'https://www.escook.cn/api/cart'
          })
            store.commit('setGoodsList',res.data.list)
        }
    },
    getters: {
        totalCount(state) {
           return state.goodList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum+=obj.goods_count
                }
                return sum
            },0)
            
        },
        totalPrice(state) {
           return state.goodList.reduce((sum, obj) => {
               if (obj.goods_state) {
                   sum+=obj.goods_count * obj.goods_price
               }
               return sum
           },0)
        },
        isAll(state) {
            // set(val) {
            //     // val就是关联表单的值(true/false)
            //     this.$emit("changeAll", val);
            //   },
            //   get() {
            //     // 查找小选框关联的属性有没有不符合勾选的条件
            //     // 直接原地false
            //     return this.arr.every((obj) => obj.goods_state === true);
            //   }
           //  if (state.isAll == true) {
           //     state.goodList.forEach(item => {
           //         item.goods_state =true
           //     })
           //      return
           //  }
            
            return state.goodList.every(obj => obj.goods_state == true)
            }
    },
    modules:{}
}

export default cartModules